﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AMStudio.Common;
using Microsoft.Practices.ServiceLocation;
using AMStudio.DelegateDispather;
using AMStudio.Windows.Forms;
using System.Diagnostics;
using AMStudio.Log;
using AccessDB;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using System.Threading;
using System.Runtime.InteropServices; 
//using Microsoft.Practices.Unity;
//using Microsoft.Practices.Unity.Configuration;

namespace AMStudio.UserInterface
{
    public partial class BaseUI : AWinFormShell
    {
        private bool loginSuccess = false;
        //private MaterialForm materialForm;
        private DataTable materialDT = null;

        public BaseUI()
        {
            //LoginForm login = new LoginForm();

            //if (login.ShowDialog() == DialogResult.OK)
            //{
            //    loginSuccess = true;

            //}
            //else
            //{
            //    this.Visible = false;
            //    Application.Exit();
            //}
            InitializeComponent();
            //this.Tag = this.GetHashCode();
            this.MaximizedBounds = Screen.PrimaryScreen.WorkingArea;
            float a = 0.12f;
            string b = a.ToString("0.00");
        }

        private void BaseUI_Load(object sender, EventArgs e)
        {
            //if (!loginSuccess)
            //{
            //    Application.Exit();
            //    return;
            //}

            this.Initialize();
            //container = new UnityContainer();
            //container.LoadConfiguration();
            this.ActiveModule("MainUI");
            base.SubscribeEvent("MANAGER_RET");
            this.ErrorList.TreeItemChecked += new EventHandler<ItemCheckedEventArgs>(ErrorList_TreeItemChecked);
            this.ErrorList.ItemSelectionChanged += new ListViewItemSelectionChangedEventHandler(ErrorList_ItemSelectionChanged);
            AEventManager myManager = ServiceLocator.Current.GetInstance<IEventManager>("EventManager") as AEventManager;
            //int a = myManager.GetHashCode();
            myManager.RunAsync();
            EventBroker.RegisterPublisher("SET_USER_PRIVILIGE", this, "SetUserPriviligeEvent");
            //EventBroker.RegisterPublisher("SET_LANGUAGE", this, "SetLanguageEvent");   
            SetUserPrivilige();

            User current = UserDB.CurrentLoginUser;
            switch (current.AuthorizationSet)
            {
                case 0:
                    this.buttonItem3.Enabled = true;
                    this.buttonItem39.Enabled = true;
                    break;
                case 1:
                case 2:
                default:
                    this.buttonItem3.Enabled = false;
                    this.buttonItem39.Enabled = false;
                    break;
            }
            materialList.DataSource = materialDT;
            materialList.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
            materialList.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
            
        }

        void ErrorList_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            //throw new NotImplementedException();
            if (ErrorList.SelectedItems != null)
            {
                if (ErrorList.SelectedItems.Count > 0)
                {
                    string code = ErrorList.SelectedItems[0].SubItems[0].Text.ToString().Trim();
                    //int st_index = int.Parse(code.Substring(0, 2));
                    SendMessage("ACTIVE_ERROR", code);
                }
            }
        }

        void ErrorList_TreeItemChecked(object sender, ItemCheckedEventArgs e)
        {
            string code = e.Item.SubItems[0].Text.ToString().Trim();
            //int st_index = int.Parse(code.Substring(0, 2));
            SendMessage("ACTIVE_ERROR", code);

        }

        protected override void Language_RfreshTag(LanguageItem item)
        {
            base.Language_RfreshTag(item);

            if (item.RelatedControl is BaseUI)
            {

                if ((item != null) && (item.Language[LanguageString] != null))
                {
                    string[] titles = item.Language[LanguageString].ToString().Split(new string[] { "||" }, StringSplitOptions.None);

                    if (titles.Length > 0)
                    {
                        this.ribbonOperation.Text = titles[0];
                        if (titles.Length > 1)
                        {
                            this.ribbonProduction.Text = titles[1];
                            if (titles.Length > 2)
                            {
                                this.ribbonStatistics.Text = titles[2];
                                if (titles.Length > 3)
                                {
                                    this.ribbonManagement.Text = titles[3];
                                    if (titles.Length > 4)
                                    {

                                        this.buttonItemLogin.Text = titles[4];

                                        if (titles.Length > 5)
                                        {
                                            this.buttonItemClose.Text = titles[5];
                                        }
                                    }
                                }
                            }
                        }
                    }

                    this.ribbonControl1.Refresh();

                }


            }

            if (item.RelatedControl is DevComponents.DotNetBar.RibbonBar)
            {
                DevComponents.DotNetBar.RibbonBar bar = item.RelatedControl as DevComponents.DotNetBar.RibbonBar;
                if (bar.Items.Count > 0)
                {
                    if ((item != null) && (item.Language[LanguageString] != null))
                    {
                        string[] titles = item.Language[LanguageString].ToString().Split(new string[] { "||" }, StringSplitOptions.None);
                        if (titles.Length >= bar.Items.Count + 1)
                        {
                            bar.Text = titles[0];

                            for (int i = 0; i < bar.Items.Count; i++)
                            {
                                bar.Items[i].Text = titles[i + 1];
                            }
                        }
                    }
                    item.RelatedControl.Refresh();
                }
            }

            if (item.RelatedControl.Name.ToString().ToUpper()=="ERRORLIST")
            {
                string[] titles = item.Language[LanguageString].ToString().Split(new string[] { "||" }, StringSplitOptions.None);

                if (titles.Length >= 3)
                {
                    for (int i = 0; i < titles.Length; i++)
                    {
                        this.ErrorList.Columns[i].Text = titles[i];
                    }
                }
            }

            if (item.RelatedControl.Name.ToString().ToUpper() == "CONDITIONLIST")
            {
                string[] titles = item.Language[LanguageString].ToString().Split(new string[] { "||" }, StringSplitOptions.None);

                if (titles.Length >= 3)
                {
                    for (int i = 0; i < titles.Length; i++)
                    {
                        this.ConditionList.Columns[i].Text = titles[i];
                    }
                }
            }
        }


        protected override void Language_InitializeControl(Control UIControl)
        {
            base.Language_InitializeControl(UIControl);
            if (UIControl is BaseUI)
            {
                LanguageItem item = LanguageDB.UIDBTags[this.UIName + "."] as LanguageItem;
                if ((item!=null) && (item.Language[LanguageString]!=null))
                {
                    string[] titles = item.Language[LanguageString].ToString().Split(new string[] { "||" }, StringSplitOptions.None);

                    if (titles.Length > 0)
                    {
                        this.ribbonOperation.Text = titles[0];
                        if (titles.Length > 1)
                        {
                            this.ribbonProduction.Text = titles[1];
                            if (titles.Length > 2)
                            {
                                this.ribbonStatistics.Text = titles[2];
                                if (titles.Length > 3)
                                {
                                    this.ribbonManagement.Text = titles[3];

                                    if (titles.Length > 4)
                                    {

                                        this.buttonItemLogin.Text = titles[4];

                                        if (titles.Length>5)
                                        {
                                            this.buttonItemClose.Text = titles[5];
                                        }
                                    }
                                }
                            }
                        }
                    }

                    this.ribbonControl1.Refresh();
                   
                }
                
                
            }

            if (UIControl is DevComponents.DotNetBar.RibbonBar)
            {
                DevComponents.DotNetBar.RibbonBar bar = UIControl as DevComponents.DotNetBar.RibbonBar;
                if (bar.Items.Count > 0)
                {
                    LanguageItem item = LanguageDB.UIDBTags[this.UIName + "." + bar.Name] as LanguageItem;
                    if ((item != null) && (item.Language[LanguageString] != null))
                    {
                        string[] titles = item.Language[LanguageString].ToString().Split(new string[] { "||" }, StringSplitOptions.None);
                        if (titles.Length >= bar.Items.Count + 1)
                        {
                            bar.Text = titles[0];

                            for (int i = 0; i < bar.Items.Count; i++)
                            {
                                bar.Items[i].Text = titles[i + 1];
                            }
                        }
                    }
                    bar.Refresh();
                }
            }



            if (UIControl.Name.ToString().ToUpper() == "ERRORLIST")
            {
                ListView bar = UIControl as ListView;


                LanguageItem item = LanguageDB.UIDBTags[this.UIName + "." + bar.Name] as LanguageItem;
                if ((item != null) && (item.Language[LanguageString] != null))
                {
                    string[] titles = item.Language[LanguageString].ToString().Split(new string[] { "||" }, StringSplitOptions.None);

                    if (titles.Length >= 3)
                    {
                        for (int i = 0; i < titles.Length; i++)
                        {
                            this.ErrorList.Columns[i].Text = titles[i];
                        }
                    }
                }

            }

            if (UIControl.Name.ToString().ToUpper() == "CONDITIONLIST")
            {
                ListView bar = UIControl as ListView;

                LanguageItem item = LanguageDB.UIDBTags[this.UIName + "." + bar.Name] as LanguageItem;
                if ((item != null) && (item.Language[LanguageString] != null))
                {
                    string[] titles = item.Language[LanguageString].ToString().Split(new string[] { "||" }, StringSplitOptions.None);

                    if (titles.Length >= 3)
                    {
                        for (int i = 0; i < titles.Length; i++)
                        {
                            this.ConditionList.Columns[i].Text = titles[i];
                        }
                    }
                }

            }


        }


        public event EventHandler SetUserPriviligeEvent = null;
        private void SetUserPrivilige()
        {
            User current = UserDB.CurrentLoginUser;
            this.Text ="Domino Assembly Line"+ current.UserName;
            this.ribbonControl1.TitleText = "<b>Domino Assembly Line (User:" + current.UserName + " login at " + DateTime.Now.ToLocalTime() + ")</b>";
            //this.ribbonControl1.Refresh();
            switch (current.AuthorizationSet)
            {
                case 0:
                    this.ribbonManagement.Enabled = true;
                    this.ribbonProduction.Enabled = true;
                    this.buttonItem3.Enabled = true;
                    this.buttonItem39.Enabled = true;
                    break;
                case 1:
                    this.ribbonManagement.Enabled = false;
                    this.ribbonProduction.Enabled = true;
                    this.buttonItem3.Enabled = false;
                    this.buttonItem39.Enabled = false;
                    break;
                case 2:
                default:
                    this.ribbonProduction.Enabled = false;
                    this.ribbonManagement.Enabled = false;
                    this.buttonItem3.Enabled = false;
                    this.buttonItem39.Enabled = false;
                    break;
            }
            SetUserPriviligeEvent(current, null);
            Language_InitializeControl(this);

            if (errors != null)
            {
                ErrorList.Items.Clear();
                foreach (MachineInformationItem item in errors.Values)
                {
                    AMStudio.Windows.Forms.TreeListItem treeItem = new AMStudio.Windows.Forms.TreeListItem(item.Code);
                    string msg = string.Empty;
                    treeItem.SubItems.Add(item.Station);
                    if (LanguageString == "中文")
                    {
                        msg = RuntimeDB.Errors_CN[item.Code].Message;
                        msg = msg.Replace(@"\\", "\\");
                        msg = msg.Replace(@"\n", "\n");
                        treeItem.SubItems.Add(msg);
                        treeItem.ToolTipText = msg;
                    }
                    else
                    {
                        msg = item.Message;
                        msg = msg.Replace(@"\\", "\\");
                        msg = msg.Replace(@"\n", "\n");
                        treeItem.SubItems.Add(msg);
                        treeItem.ToolTipText = msg;
                    }
                    treeItem.SubItems.Add(item.Address);
                    ErrorList.Items.Add(treeItem);
                }
                ErrorList.Invalidate();
            }

            if (conditions != null)
            {
                ConditionList.Items.Clear();
                foreach (MachineInformationItem item in conditions.Values)
                {
                    AMStudio.Windows.Forms.TreeListItem treeItem = new AMStudio.Windows.Forms.TreeListItem(item.Code);
                    string msg = string.Empty;
                    treeItem.SubItems.Add(item.Station);
                    if (LanguageString == "中文")
                    {
                        msg = RuntimeDB.Conditions_CN[item.Code].Message;
                        msg = msg.Replace(@"\\", "\\");
                        msg = msg.Replace(@"\n", "\n");
                        treeItem.SubItems.Add(msg);
                        treeItem.ToolTipText = msg;
                    }
                    else
                    {
                        msg = item.Message;
                        msg = msg.Replace(@"\\", "\\");
                        msg = msg.Replace(@"\n", "\n");
                        treeItem.SubItems.Add(msg);
                        treeItem.ToolTipText = msg;
                    }
                    treeItem.SubItems.Add(item.Address);
                    ConditionList.Items.Add(treeItem);
                }
                ConditionList.Invalidate();
            }

        }
        //private IUnityContainer container;
        public override void ActiveModule(string UIName)
        {
            AWinFormModule activeModule = ServiceLocator.Current.GetInstance<AWinFormModule>(UIName);
            activeModule.ActivateUI();
            if (this.MainPanel.Controls.Count > 0)
            {
                this.MainPanel.Controls.RemoveAt(0);
            }
            this.MainPanel.Controls.Add(activeModule);
            activeModule.Dock = DockStyle.Fill;
        }

        private void buttonItem1_Click(object sender, EventArgs e)
        {
            this.ActiveModule("MainUI");
        }

        Dictionary<string, MachineInformationItem> errors = null;
        Dictionary<string, MachineInformationItem> conditions = null;
        Dictionary<string, MachineInformationItemStatistics> errors_statistics = new Dictionary<string, MachineInformationItemStatistics>();
        int[] Stn_nestID = new int[8];
        protected override void BackGroud_EventHandler(object sender, StationEventArgs e)
        {
            if (e.From == "MANAGER")
            {
                switch (e.Command)
                {
                    case "ERROR_TAKE":
                        {
                            object[] OV = e.Value as object[];
                            ErrorList.Items.Clear();
                            errors = OV[0] as Dictionary<string, MachineInformationItem>;
                            Stn_nestID = (int[])OV[1];

                            foreach (MachineInformationItem item in errors.Values)
                            {
                                AMStudio.Windows.Forms.TreeListItem treeItem = new AMStudio.Windows.Forms.TreeListItem(item.Code);
                                string msg = string.Empty;
                                treeItem.SubItems.Add(item.Station);
                                if (LanguageString == "中文")
                                {
                                    msg = RuntimeDB.Errors_CN[item.Code].Message;
                                    msg = msg.Replace(@"\\", "\\");
                                    msg = msg.Replace(@"\n", "\n");
                                    treeItem.SubItems.Add(msg);
                                    treeItem.ToolTipText = msg;
                                    //Logger.Write(DateTime.Now.ToString() + RuntimeDB.Errors_CN[item.Code].Message, "ERRORINFO", 0, 0, System.Diagnostics.TraceEventType.Information, "", null);
                                }
                                else
                                {
                                    msg = item.Message;
                                    msg = msg.Replace(@"\\", "\\");
                                    msg = msg.Replace(@"\n", "\n");
                                    treeItem.SubItems.Add(msg);
                                    treeItem.ToolTipText = msg;
                                    //Logger.Write(DateTime.Now.ToString() + item.Message, "ERRORINFO", 0, 0, System.Diagnostics.TraceEventType.Information, "", null);
                                }
                                treeItem.SubItems.Add(item.Address);
                                ErrorList.Items.Add(treeItem);

                                #region 错误消息统计添加

                                if (!errors_statistics.ContainsKey(item.Code))
                                {
                                    MachineInformationItemStatistics itemstatistics = new MachineInformationItemStatistics();
                                    DateTime dt = DateTime.Now;

                                    int stn = 1;
                                    try
                                    {
                                        stn = Int32.Parse(item.Station.Substring(3, 2));
                                        if (stn > Stn_nestID.Length)
                                            stn = 1;
                                    }
                                    catch
                                    { }

                                    itemstatistics.StartTime = dt;
                                    itemstatistics.EndTime = dt;
                                    itemstatistics.DurationTime = itemstatistics.EndTime - itemstatistics.StartTime;
                                    itemstatistics.NestID = Stn_nestID[stn - 1];
                                    itemstatistics.Item = item;

                                    errors_statistics.Add(item.Code, itemstatistics);

                                }

                                #endregion
                            }
                            #region 错误消息统计消除时移除报警项，并写LOG
                            List<string> key_del = new List<string>();
                            foreach (string keystr in errors_statistics.Keys)
                            {
                                if (!errors.ContainsKey(keystr))
                                {
                                    key_del.Add(keystr);
                                }
                            }

                            foreach (string keystr in key_del)
                            {
                                if (errors_statistics.ContainsKey(keystr))
                                {
                                    DateTime dt = DateTime.Now;
                                    errors_statistics[keystr].EndTime = dt;
                                    errors_statistics[keystr].DurationTime = errors_statistics[keystr].EndTime - errors_statistics[keystr].StartTime;

                                    if (LanguageString == "中文")
                                    {
                                        Logger.Write(errors_statistics[keystr].EndTime.ToString() + "," + errors_statistics[keystr].StartTime.ToString() + "," + errors_statistics[keystr].DurationTime.ToString() + "," + RuntimeDB.Errors_CN[errors_statistics[keystr].Item.Code].Message + ",NestID=" + errors_statistics[keystr].NestID.ToString(), "ERRORINFO", 0, 0, System.Diagnostics.TraceEventType.Information, "", null);
                                    }
                                    else
                                    {
                                        Logger.Write(errors_statistics[keystr].EndTime.ToString() + "," + errors_statistics[keystr].StartTime.ToString() + "," + errors_statistics[keystr].DurationTime.ToString() + "," + errors_statistics[keystr].Item.Message + ",NestID=" + errors_statistics[keystr].NestID.ToString(), "ERRORINFO", 0, 0, System.Diagnostics.TraceEventType.Information, "", null);
                                    }
                                    errors_statistics.Remove(keystr);
                                }
                            }
                            key_del.Clear();

                            #endregion

                            if (ErrorList.Items.Count >= 1)
                            {
                                string code = string.Empty;
                                if (ErrorList.CheckedItems.Count == 0)
                                {
                                    ErrorList.Items[0].Checked = true;
                                    code = ErrorList.Items[0].Text.Trim();

                                }
                                else
                                {
                                    code = ErrorList.CheckedItems[0].SubItems[0].Text.Trim();
                                }
                                SendMessage("ACTIVE_ERROR", code);
                            }

                            ErrorList.Invalidate();
                        }
                        break;
                    case "CONDITION_TAKE":
                        {
                            ConditionList.Items.Clear();
                            conditions = e.Value as Dictionary<string, MachineInformationItem>;
                            foreach (MachineInformationItem item in conditions.Values)
                            {
                                AMStudio.Windows.Forms.TreeListItem treeItem = new AMStudio.Windows.Forms.TreeListItem(item.Code);
                                string msg = string.Empty;
                                treeItem.SubItems.Add(item.Station);
                                if (LanguageString == "中文")
                                {
                                    msg = RuntimeDB.Conditions_CN[item.Code].Message;
                                    msg = msg.Replace(@"\\", "\\");
                                    msg = msg.Replace(@"\n", "\n");
                                    treeItem.SubItems.Add(msg);
                                    treeItem.ToolTipText = msg;
                                }
                                else
                                {
                                    msg = item.Message;
                                    msg = msg.Replace(@"\\", "\\");
                                    msg = msg.Replace(@"\n", "\n");
                                    treeItem.SubItems.Add(msg);
                                    treeItem.ToolTipText = msg;
                                }
                                treeItem.SubItems.Add(item.Address);
                                ConditionList.Items.Add(treeItem);
                            }
                            ConditionList.Invalidate();
                        }
                        break;
                    case "EMPTY_LINE":
                        {
                            bool bV = bool.Parse(e.Value.ToString());

                            this.buttonItem14.Checked = bV;
                            this.buttonItem19.Checked = bV;
                            this.buttonItem21.Checked = bV;
                            this.buttonItem35.Checked = bV;
                            if (this.buttonItem14.Checked)
                            {
                                this.buttonItem14.Image = AMStudio.UserInterface.Properties.Resources.empty;
                                this.buttonItem19.Image = AMStudio.UserInterface.Properties.Resources.empty;
                                this.buttonItem21.Image = AMStudio.UserInterface.Properties.Resources.empty;
                                this.buttonItem35.Image = AMStudio.UserInterface.Properties.Resources.empty;
                            }
                            else
                            {
                                this.buttonItem14.Image = AMStudio.UserInterface.Properties.Resources.empty_full;
                                this.buttonItem19.Image = AMStudio.UserInterface.Properties.Resources.empty_full;
                                this.buttonItem21.Image = AMStudio.UserInterface.Properties.Resources.empty_full;
                                this.buttonItem35.Image = AMStudio.UserInterface.Properties.Resources.empty_full;
                            }
                        }
                        break;
                    case "TRIAL_RUN":
                        {
                            bool bV = bool.Parse(e.Value.ToString());
                            this.buttonItem39.Checked = bV;
                            this.buttonItem40.Checked = bV;
                            if (this.buttonItem39.Checked)
                            {
                                this.buttonItem39.Image = AMStudio.UserInterface.Properties.Resources.trialrun;
                                this.buttonItem40.Image = AMStudio.UserInterface.Properties.Resources.trialrun;
                            }
                            else
                            {
                                this.buttonItem39.Image = AMStudio.UserInterface.Properties.Resources.trialrun_stop;
                                this.buttonItem40.Image = AMStudio.UserInterface.Properties.Resources.trialrun_stop;
                            }
                            if(!e.Status && bV)
                                System.Windows.Forms.MessageBox.Show("已经激活离线模式！", "警告",MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        break;
                    case "REWORK":
                        {
                            bool bV = bool.Parse(e.Value.ToString());
                            this.buttonItem3.Checked = bV;
                            if (this.buttonItem3.Checked)
                            {
                                this.buttonItem3.Image = AMStudio.UserInterface.Properties.Resources.rework;
                            }
                            else
                            {
                                this.buttonItem3.Image = AMStudio.UserInterface.Properties.Resources.normal_work;
                            }
                            if (!e.Status && bV)
                                System.Windows.Forms.MessageBox.Show("已经激活返工模式！", "警告", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        break;
                    #region ITAC RELATED
                        /*
                    case "MATERIAL_QUANTITY":
                        {
                            object[] obj = (object[])e.Value;
                            this.textBoxX2.Text = obj[0].ToString();
                            this.textBoxX1.Text = obj[1].ToString();
                            if (textBoxX2.Text == "1")
                            {
                                //MessageBox.Show("物料已经用完，请扫描新的物料箱号！");
                                //BaseUI form = new BaseUI();
                                //System.Threading.Thread thread = new System.Threading.Thread(form.ShowMaterialOver);
                                //thread.Start();
                                textBoxX7.Text = "";
                                textBoxX1.Text = "";
                                textBoxX2.Text = "";
                                textBoxX7.Focus();
                            }
                        }
                        break;
                    case "CHECK_MATERIAL_ERROR":
                        {
                            MessageBox.Show("箱号不对！请重新扫描物料箱号！");
                            this.textBoxX7.Text = "";
                            textBoxX7.Focus();
                        }
                        break;
                    case "CHECK_MATERIAL_OK":
                        {
                            MessageBox.Show("物料已经激活成功！");
                        }
                        break;
                    case "DISPATCH_INFO":
                        {
                            object[] obj = (object[])e.Value;
                            if (obj[0].ToString() != string.Empty)
                                this.textBoxX5.Text = obj[0].ToString();
                            if (obj[1].ToString() != string.Empty)
                                this.textBoxX6.Text = obj[1].ToString();
                            if (obj[2].ToString() != string.Empty)
                            {
                                this.textBoxX10.Text = obj[2].ToString();
                            }
                        }
                        break;
                    case "SET_EXISTING_BOX_ERROR":
                        {
                            MessageBox.Show("箱号不对，请重新扫描！");
                            this.comboBox1.Text = "";
                            this.comboBox1.Focus();
                        }
                        break;
                    case "SET_EXISTING_BOX_OK":
                        {
                            MessageBox.Show("箱号已经激活成功，可以开始拼箱！");
                        }
                        break;
                    case "CUSTOMER_SN":
                        {
                            textBoxX9.Text = textBoxX8.Text;
                            textBoxX8.Text = textBoxX3.Text;
                            textBoxX3.Text = e.Value.ToString();
                        }
                        break;
                    case "DISPATCH_OVER":
                        {
                            BaseUI form = new BaseUI();
                            System.Threading.Thread thread = new System.Threading.Thread(form.ShowDispatch);
                            thread.Start();
                        }
                        break;
                    case "CLEAR":
                        {
                            textBoxX1.Text = "";
                            textBoxX2.Text = "";
                            textBoxX3.Text = "";
                            textBoxX5.Text = "";
                            textBoxX6.Text = "";
                            textBoxX7.Text = "";
                            textBoxX8.Text = "";
                            textBoxX9.Text = "";
                            textBoxX10.Text = "";
                            comboBox1.Text = "";
                        }
                        break;
                         */
                    #endregion
                    case "GETBOMITEMS":
                        {
                            object[] obj = (object[])e.Value;
                            switch (int.Parse(obj[1].ToString()))
                            {
                                case 0:
                                    {
                                        materialDT = (DataTable)obj[0];
                                        materialList.DataSource = materialDT;
                                        this.materialList.Refresh();
                                    }
                                    break;
                                case 1:
                                    {
                                        materialDT = (DataTable)obj[0];
                                        materialList.DataSource = materialDT;
                                        this.materialList.Refresh();
                                        System.Windows.Forms.MessageBox.Show("工单激活成功，请扫描物料！！！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                    }
                                    break;
                                case 2:
                                    {
                                        materialDT = (DataTable)obj[0];
                                        materialList.DataSource = materialDT;
                                        this.materialList.Refresh();
                                        System.Windows.Forms.MessageBox.Show("工单激活失败，请检查产品号是否与服务器工单的产品号一致！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    }
                                    break;
                                case 3:
                                    {
                                        materialDT = (DataTable)obj[0];
                                        materialList.DataSource = materialDT;
                                        this.materialList.Refresh();
                                        System.Windows.Forms.MessageBox.Show("扫描物料成功！","提示",MessageBoxButtons.OK, MessageBoxIcon.Information);
                                        textBoxX7.Text = "";
                                    }
                                    break;
                                case 4:
                                    {
                                        System.Windows.Forms.MessageBox.Show("物料箱号不对，请重新扫描！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                        textBoxX7.Text = "";
                                    }
                                    break;
                                default:
                                    break;
                            }
                            for (int i = 0; i < materialList.Columns.Count; i++)
                            {
                                materialList.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
                            }
                            materialList.Refresh();

                            foreach (DataRow row in materialDT.Rows)
                            {
                                if (row["sn"].ToString() != ""
                                    && (int.Parse(row["quantity"].ToString())) <= 0)
                                {
                                    //todo 扫描物料下位机置位
                                    //WritePLC(DialTablePLC, "E2221.06", "True");
                                    SendMessage("SET_POINT", "E2221.06");
                                    string str = "物料已经用完，请扫描物料：" + row["compName"] + "-" + row["partNo"];
                                    //MessageBox.Show(str, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                    //Invoke((EventHandler)delegate { MessageBox.Show(str, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); });
                                    ShowAsyncMSG(str, "提示");
                                    this.textBoxX7.Focus();
                                }
                            }
                            strList.Clear();
                            byteList.Clear();
                        }
                        break;
                    case "UPLOADSTATE":
                        {
                            object[] obj = (object[])e.Value;
                            txtSN.Text = obj[0].ToString();
                            //txtQuantity.Text = obj[1].ToString();
                            //txtTotalQuantity.Text = obj[2].ToString();
                            //materialDT = (DataTable)obj[3];
                            //materialList.DataSource = materialDT;
                            //int sum = int.Parse(obj[4].ToString());
                            //foreach (DataRow row in materialDT.Rows)
                            //{
                            //    if ((int.Parse(row["quantity"].ToString())-sum) == 0)
                            //    {
                            //        //todo 扫描物料下位机置位
                            //        //WritePLC(DialTablePLC, "E2221.06", "True");
                            //        SendMessage("SET_POINT", "E2221.06");
                            //        string str = "物料已经用完，请扫描物料：" + row["compName"] + "-" + row["partNo"];
                            //        MessageBox.Show(str, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            //        this.textBoxX7.Focus();
                            //    }
                            //}
                        }
                        break;
                    case "ECUSN":
                        {
                            txtSN.Text = e.Value.ToString();
                        }
                        break;
                    case "ACTIVE_MAINUI":
                        {
                            this.ActiveModule("MainUI");
                        }
                        break;
                    case "CHECK_CONNECTION":
                        {
                            System.Windows.Forms.MessageBox.Show("ITAC连接断开，请检查！", "提示",MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        break;
                    case "MSG":
                        {
                            System.Windows.Forms.MessageBox.Show("MSG: " + e.Value.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        break;
                    case "ASYNCMSG":
                        {
                            ShowAsyncMSG(e.Value.ToString(), "提示");
                        }
                        break;
                    case "PRODUCTCHECK":
                        {
                            //if (MessageBox.Show("是否检查产品类型(进入返工，离线模式)?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                            {
                                SendMessage("PRODUCTCHECK", true);
                            }
                            //else
                            //{
                            //    SendMessage("ST11PRODUCTCHECK", false);
                            //}
                        }
                        break;
                    case "REFRESH_CAMERASTATUS":
                        {
                            object[] obj = (object[])e.Value;

                            switch (obj[0].ToString())
                            {
                                #region stn1
                                case "STN1":
                                    {
                                        switch (int.Parse(obj[1].ToString()))
                                        {
                                            case 0:
                                                { st1CameraStatus.ForeColor = System.Drawing.Color.DarkGray; }
                                                break;
                                            case 1:
                                                { st1CameraStatus.ForeColor = System.Drawing.Color.Aqua; }
                                                break;
                                            case 2:
                                                { st1CameraStatus.ForeColor = System.Drawing.Color.Green; }
                                                break;
                                            case 3:
                                                { st1CameraStatus.ForeColor = System.Drawing.Color.Red; }
                                                break;
                                            case 4:
                                                { st1CameraStatus.ForeColor = System.Drawing.Color.Yellow; }
                                                break;
                                        }
                                    }
                                    break;
                                #endregion
                                #region stn5
                                case "STN5":
                                    {
                                        switch (int.Parse(obj[1].ToString()))
                                        {
                                            case 0:
                                                { st5CameraStatus.ForeColor = System.Drawing.Color.DarkGray; }
                                                break;
                                            case 1:
                                                { st5CameraStatus.ForeColor = System.Drawing.Color.Aqua; }
                                                break;
                                            case 2:
                                                { st5CameraStatus.ForeColor = System.Drawing.Color.Green; }
                                                break;
                                            case 3:
                                                { st5CameraStatus.ForeColor = System.Drawing.Color.Red; }
                                                break;
                                            case 4:
                                                { st5CameraStatus.ForeColor = System.Drawing.Color.Yellow; }
                                                break;
                                        }
                                    }
                                    break;
                                #endregion
                            }
                        }
                        break;
                    case "PRODUCTCHECK_STATUS":
                        {
                            bool ProductCheck = e.Status;
                            bool[] StnStatus = (bool[])e.Value;
                            const string red = "\"#ED1C24\"";
                            const string green = "\"#22B14C\"";
                            string[] StnColors = new string[2];
                            if (ProductCheck)
                            {
                                try
                                {
                                    StnColors[0] = StnStatus[0] ? green : red;
                                    StnColors[1] = StnStatus[1] ? green : red;
                                    //<b><i><font color="#22B14C">OK</font> <font color="#ED1C24">NG</font></i></b>
                                    labSt5Stu.Text = "<b><i><font color=" + StnColors[0] + ">OK</font> <font color=" + StnColors[1] + ">NG</font></i></b>";
                                    
                                }
                                catch
                                {

                                }

                                labSt5Stu.Visible = true;
                            }
                            else
                            {
                                labSt5Stu.Text = "<font color=\"#22B14C\"><b><i>OK NG</i></b></font>";
                                labSt5Stu.Visible = false;
                            }

                        }
                        break;
                }
            }
        }

        public string Msg;
        public string Cpation;
        public void ShowAsyncMSG(string msg, string caption)
        {
            Msg = msg;
            Cpation = caption;
            tmrShowMsg.Enabled = true;
        }

        [DllImport("User32.dll")]
        public static extern int MessageBox(int hWnd, string Text, string Caption, int Type);
        public readonly int MB_OK = 0x00000000;
        public readonly int MB_ICONINFORMATION = 0x00000040;
        public readonly int MB_DEFBUTTON1 = 0x00000000;
        public readonly int MB_TOPMOST = 0x00040000;
        public readonly int MB_APPLMODAL = 0x00000000;
        private void tmrShowMsg_Tick(object sender, EventArgs e)
        {
            tmrShowMsg.Enabled = false;

            Thread thdSub = new Thread(new ThreadStart(() =>
            {
                MessageBox(0, Msg, Cpation, MB_OK | MB_ICONINFORMATION | MB_DEFBUTTON1 | MB_TOPMOST | MB_APPLMODAL);
            }));
            thdSub.Start();
        }

        protected override void UIDB_RfreshTag(Common.UserInterfaceItem item)
        {
            if (item.RelatedControl is SimpleEllipse)
            {
                if ((bool)item.value)
                {
                    item.RelatedControl.ForeColor = System.Drawing.Color.Green;
                }
                else
                {
                    item.RelatedControl.ForeColor = System.Drawing.Color.DarkGray;
                }
            }
            else if (item.RelatedControl is DevComponents.DotNetBar.RibbonBar)
            {
                DevComponents.DotNetBar.RibbonBar button = item.RelatedControl as DevComponents.DotNetBar.RibbonBar;
                int modeState = (int)item.value;
                //this.buttonAuto.Checked = false;
                this.buttonCycleStop.Checked = false;
                this.buttonManual.Checked = false;
                this.buttonReset.Checked = false;
                if (modeState == 0)
                {
                    this.buttonAuto.Checked = true;
                }
                else if (modeState == 2)
                {
                    this.buttonManual.Checked = true;
                    this.buttonAuto.Checked = false;
                }
                else if (modeState == 4)
                {
                    this.buttonReset.Checked = true;
                    this.buttonAuto.Checked = false;
                }
                else if (modeState == 8)
                {
                    this.buttonAuto.Checked = true;
                }
                else if (modeState == 16)
                {
                    this.buttonCycleStop.Checked = true;
                    this.buttonAuto.Checked = false;
                }
                else
                {
                    this.buttonAuto.Checked = false;
                }
            }
            else if (item.RelatedControl is DevComponents.DotNetBar.ButtonX)
            {
                DevComponents.DotNetBar.ButtonX button = item.RelatedControl as DevComponents.DotNetBar.ButtonX;

                if (button.Name == "buttonItem17")
                {
                    nNestConfig = (int)item.value;
                }

            }

            //if (item.RelatedControl.Name.ToString().ToUpper()=="SIMPLEELLIPSEAUTO")
            //{
            //    bAuto = (bool)item.value;
            //}
        }
        private bool bAuto = false;


        private int nNestConfig = 0;

        protected override void UIDB_ConnectTagAction(Common.UserInterfaceItem item)
        {
            item.RelatedControl.Click += (sender, e) =>
            {
                DevComponents.DotNetBar.ButtonX button = item.RelatedControl as DevComponents.DotNetBar.ButtonX;
                //if (button.Checked)
                //{
                SendMessage("UIITEM_ACTION", item);
                //}
            };
        }

        private void buttonReset_Click(object sender, EventArgs e)
        {
            SendMessage("MODE_REQUEST", 1);
        }

        private void buttonAuto_Click(object sender, EventArgs e)
        {
            SendMessage("MODE_REQUEST", 2);
        }

        private void buttonManual_Click(object sender, EventArgs e)
        {
            SendMessage("MODE_REQUEST", 0);
        }

        private void buttonCycleStop_Click(object sender, EventArgs e)
        {
            SendMessage("MODE_REQUEST", 3);
        }

        private void buttonItem30_Click(object sender, EventArgs e)
        {
            IUserInterface login = ServiceLocator.Current.GetInstance<IUserInterface>("LoginForm");
            login.ActivateUI();

            SetUserPrivilige();
        }

        private void buttonItem25_Click(object sender, EventArgs e)
        {
            IUserInterface userManager = ServiceLocator.Current.GetInstance<IUserInterface>("UserAccountsForm");
            userManager.ActivateUI();
        }

        private void buttonItem15_Click(object sender, EventArgs e)
        {
            IUserInterface userManager = ServiceLocator.Current.GetInstance<IUserInterface>("WorkorderForm");
            ((WorkorderForm)userManager).StationAuto = this.buttonAuto.Checked;
            userManager.ActivateUI();
        }

        private void buttonItem16_Click(object sender, EventArgs e)
        {
            IUserInterface userManager = ServiceLocator.Current.GetInstance<IUserInterface>("ArticlesForm");
            userManager.ActivateUI();
        }

        private void buttonItem27_Click(object sender, EventArgs e)
        {
            Process.Start("explorer.exe", @"Log\Traceability");
        }

        private void buttonItem28_Click(object sender, EventArgs e)
        {
            Process.Start("explorer.exe", @"Log\ErrorInfo");
        }

        private void buttonItem29_Click(object sender, EventArgs e)
        {
            Process.Start("explorer.exe", @"Log\WorkOrder");
        }

        private void buttonItem14_Click(object sender, EventArgs e)
        {
            SendMessage("EMPTY_LINE", !this.buttonItem14.Checked);
        }

        private void buttonItem12_Click(object sender, EventArgs e)
        {

        }

        private void ribbonControl1_SizeChanged(object sender, EventArgs e)
        {

        }

        private void buttonItem33_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void buttonItem14_CheckedChanged(object sender, EventArgs e)
        {
            if (this.buttonItem14.Checked)
            {
                this.buttonItem14.Image = AMStudio.UserInterface.Properties.Resources.empty;
                this.buttonItem19.Image = AMStudio.UserInterface.Properties.Resources.empty;
                this.buttonItem21.Image = AMStudio.UserInterface.Properties.Resources.empty;
                this.buttonItem35.Image = AMStudio.UserInterface.Properties.Resources.empty;
            }
            else
            {
                this.buttonItem14.Image = AMStudio.UserInterface.Properties.Resources.empty_full;
                this.buttonItem19.Image = AMStudio.UserInterface.Properties.Resources.empty_full;
                this.buttonItem21.Image = AMStudio.UserInterface.Properties.Resources.empty_full;
                this.buttonItem35.Image = AMStudio.UserInterface.Properties.Resources.empty_full;
            }

            //this.buttonItem14.Checked = bV;
            //this.buttonItem19.Checked = bV;
            //this.buttonItem21.Checked = bV;
            //this.buttonItem35.Checked = bV;
            //this.buttonItem37.Checked = bV;
        }

        private void buttonItem39_Click(object sender, EventArgs e)
        {
            if (this.buttonAuto.Checked)
            {
                System.Windows.Forms.MessageBox.Show("请切换到手动再更改运行模式!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            SendMessage("TRIAL_RUN", !this.buttonItem39.Checked);
        }

        private void buttonItem39_CheckedChanged(object sender, EventArgs e)
        {
            if (this.buttonItem40.Checked)
            {
                this.buttonItem39.Image = AMStudio.UserInterface.Properties.Resources.trialrun;
                this.buttonItem40.Image = AMStudio.UserInterface.Properties.Resources.trialrun;
            }
            else
            {
                this.buttonItem39.Image = AMStudio.UserInterface.Properties.Resources.trialrun_stop;
                this.buttonItem40.Image = AMStudio.UserInterface.Properties.Resources.trialrun_stop;
            }
        }
        private void buttonItem17_Click(object sender, EventArgs e)
        {
            //IUserInterface userManager = ServiceLocator.Current.GetInstance<IUserInterface>("NestConfigUI");
            //userManager.ActivateUI();

            NestConfigUI fNest = new NestConfigUI();

            MachineConfig config = MachineConfig.Default;

            fNest.NestCfg = config.UICfg.NestCfg;
            if (fNest.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                SendMessage("NEST_CFG", fNest.NestCfg);
                config.UICfg.NestCfg = fNest.NestCfg;

                config.SaveConfig();
            }
        }

        //IUserInterface userManager = null;
        private void buttonItem44_Click(object sender, EventArgs e)
        {
            //if (userManager == null)
            //    userManager = ServiceLocator.Current.GetInstance<IUserInterface>("MaterialForm");
            //userManager.ActivateUI();
            //materialForm.Show();
        }

        private void ribbonControl1_Resize(object sender, EventArgs e)
        {
            this.lblLogo1.Left = ribbonPanel1.ClientSize.Width - this.lblLogo1.Width-20;
            this.lblLogo2.Left = ribbonPanel1.ClientSize.Width - this.lblLogo2.Width-20;
            this.lblLogo3.Left = ribbonPanel1.ClientSize.Width - this.lblLogo3.Width-20;
            this.lblLogo4.Left = ribbonPanel1.ClientSize.Width - this.lblLogo4.Width-20;
        }

        private void buttonX3_Click(object sender, EventArgs e)
        {
            SendMessage("PRINT_TEMP_NR", txtQuantity.Text);
            //if (textBoxX10.Text == "")
            //{
            //    MessageBox.Show("没有箱号可以打印！");
            //    return;
            //}
            //SendMessage("DISPATCH", null);
            //this.textBoxX10.Text = "";
            //this.textBoxX5.Text = "";
            //this.textBoxX6.Text = "";
        }

        private void buttonX26_Click(object sender, EventArgs e)
        {
            SendMessage("REPRINT", txtQuantity.Text);
            //if (comboBox1.Text == "")
            //{
            //    MessageBox.Show("请先选择旧箱号，然后重新打印！");
            //    return;
            //}
            //SendMessage("DISPATCH_PRINT", comboBox1.Text);
        }

        private void buttonX25_Click(object sender, EventArgs e)
        {
            SendMessage("ASSEMBLY", txtQuantity.Text);
            //if (textBoxX5.Text != "" && textBoxX6.Text != textBoxX5.Text)
            //{
            //    MessageBox.Show("前一箱未做完，此时不能拼箱！");
            //    comboBox1.Text = "";
            //    return;
            //}
            //if (comboBox1.Text == "")
            //{
            //    MessageBox.Show("请先输入旧箱号，然后拼箱！");
            //    return;
            //}
            //SendMessage("SET_EXISTING_BOX", this.comboBox1.Text);
            //SendMessage("PinXiang", null);
            //this.comboBox1.Text = "";
        }

        List<string> strList = new List<string>();
        List<byte> byteList = new List<byte>();
        bool Is2DCode = false;
        private void textBoxX7_KeyPress(object sender, KeyPressEventArgs e)
        {
            errorProvider1.Clear();
            //revByte[index++] = (byte)e.KeyChar;
            if (e.KeyChar == 13)
            {
                //index = 0;
                if (Is2DCode)
                {
                    #region 二维码
                    string[] usedDataIdentifier = new string[] { "V", "P", "S", "M", "G" };
                    string[] strArray = strList.ToArray();
                    StringBuilder materialData = new StringBuilder();
                    if (usedDataIdentifier.Length > 0)
                    {
                        foreach (string identifer in usedDataIdentifier)
                        {
                            foreach (string data in strArray)
                            {
                                if (data.Trim().StartsWith(identifer))
                                    materialData.Append(data.Substring(data.IndexOf(identifer) + identifer.Length).Trim());
                            }
                        }
                        textBoxX7.Text = materialData.ToString();
                    }

                    if (textBoxX7.Text.Length > 0)
                    {
                        SendMessage("ACTIVEMATERIAL", textBoxX7.Text);
                    }
                    else
                    {
                        System.Windows.Forms.MessageBox.Show("错误条码，请扫正确的二维码!");
                        return;
                    }

                    #endregion
                }
                else
                {
                    #region 条形码
                    if (textBoxX7.Text.Length != 24)
                    {
                        errorProvider1.SetError(textBoxX7, "错误条码，请扫24位9S条码!");
                        textBoxX7.Focus();
                        textBoxX7.SelectAll();
                        return;
                    }
                    SendMessage("ACTIVEMATERIAL", textBoxX7.Text);
                    #endregion
                }
                strList.Clear();
                byteList.Clear();
            }
            else if (e.KeyChar == 29 || e.KeyChar == 30)
            {
                byte[] chars = byteList.ToArray();
                string item = Encoding.ASCII.GetString(chars, 0, chars.Length);
                strList.Add(item);
                byteList.Clear();
                Is2DCode = true;
            }
            else if (e.KeyChar == 4)
            {
                Is2DCode = true;
            }
            else
            {
                byteList.Add((byte)e.KeyChar);
                Is2DCode = false;
            }
        }

        private void comboBox1_DropDown(object sender, EventArgs e)
        {
            //DataTable dt = AccessHelper.dataTable("select top 20 * from DISPATCH ORDER BY ID DESC");
            //if (dt.Rows.Count > 0)
            //{
            //    comboBox1.DataSource = dt;
            //    comboBox1.DisplayMember = "BOXNR";
            //}
        }

        private void ShowDispatch()
        {
            //MessageBox.Show("已满箱，请粘贴标签后确认！");
            DispatchForm form = new DispatchForm();
            if (form.ShowDialog() == DialogResult.OK)
            {
                SendMessage("PinXiang", null);
            }
            SendMessage("DISPATCHED", null);
        }

        private void ShowMaterialOver()
        {
            System.Windows.Forms.MessageBox.Show("物料已经用完，请扫描新的物料箱号！");
        }

        protected override object BackGroud_Async_EventHandler(string command, object paramter)
        {
            switch (command)
            {
                case "DisplayMessageBox":
                    {
                        if (System.Windows.Forms.MessageBox.Show(this, paramter.ToString(), "提示", MessageBoxButtons.OK) == DialogResult.OK)
                        {
                            return true;
                        }
                        else
                        {
                            return false;
                        }
                    }
                    break;
            }
            return true;
        }

        private void buttonItem3_CheckedChanged(object sender, EventArgs e)
        {
            if (this.buttonItem3.Checked)
            {
                this.buttonItem3.Image = AMStudio.UserInterface.Properties.Resources.rework;
            }
            else
            {
                this.buttonItem3.Image = AMStudio.UserInterface.Properties.Resources.normal_work;
            }
        }

        private void buttonItem3_Click(object sender, EventArgs e)
        {
            if (this.buttonAuto.Checked)
            {
                System.Windows.Forms.MessageBox.Show("请切换到手动再更改运行模式!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            SendMessage("REWORK", !this.buttonItem3.Checked);
        }

        private void btnStation_Click(object sender, EventArgs e)
        {
            StationConfigUI fStation = new StationConfigUI();
            MachineConfig config = MachineConfig.Default;
            fStation.StationCfg = config.UICfg.StationCfg;
            if (fStation.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                SendMessage("STATION_CFG", fStation.StationCfg);
                config.UICfg.StationCfg = fStation.StationCfg;
                config.SaveConfig();
            }
        }

        private void buttonAuto_CheckedChanged(object sender, EventArgs e)
        {
            if (buttonAuto.Checked)
                System.Windows.Forms.MessageBox.Show("已经激活自动运行模式，请确认各个工站的使能与禁用！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void materialList_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            e.ThrowException = false;
            Logger.Write(e.ToString() + "\n rowIndex:" + e.RowIndex.ToString() + " columnIndex:" + e.ColumnIndex.ToString(), "Debug", 0, 0, System.Diagnostics.TraceEventType.Information, "", null);
        }

        private void BaseUI_FormClosed(object sender, FormClosedEventArgs e)
        {
            List<string> key_del = new List<string>();
            foreach (string keystr in errors_statistics.Keys)
            {
                key_del.Add(keystr);
            }

            foreach (string keystr in key_del)
            {
                if (errors_statistics.ContainsKey(keystr))
                {
                    DateTime dt = DateTime.Now;
                    errors_statistics[keystr].EndTime = dt;
                    errors_statistics[keystr].DurationTime = errors_statistics[keystr].EndTime - errors_statistics[keystr].StartTime;

                    if (LanguageString == "中文")
                    {
                        Logger.Write(errors_statistics[keystr].EndTime.ToString() + "," + errors_statistics[keystr].StartTime.ToString() + "," + errors_statistics[keystr].DurationTime.ToString() + "," + RuntimeDB.Errors_CN[errors_statistics[keystr].Item.Code].Message + ",NestID=" + errors_statistics[keystr].NestID.ToString() + "【软件退出】", "ERRORINFO", 0, 0, System.Diagnostics.TraceEventType.Information, "", null);
                    }
                    else
                    {
                        Logger.Write(errors_statistics[keystr].EndTime.ToString() + "," + errors_statistics[keystr].StartTime.ToString() + "," + errors_statistics[keystr].DurationTime.ToString() + "," + errors_statistics[keystr].Item.Message + ",NestID=" + errors_statistics[keystr].NestID.ToString() + "【软件退出】", "ERRORINFO", 0, 0, System.Diagnostics.TraceEventType.Information, "", null);
                    }
                    errors_statistics.Remove(keystr);
                }
            }
            key_del.Clear();

        }
    }
}